<!-- 分配用户页面 -->
<template>
  <el-dialog
    v-dialogDrag
    title="用户分配"
    :visible.sync="isDialogAssignUserShow"
    width="50%"
    :before-close="closeDialog"
  >
    <el-form class="searchForm">
      <el-form-item label="用户名称:" />
      <el-form-item>
        <el-input id="search" v-model="userQuery.name" placeholder="请输入用户名称" />
      </el-form-item>
      <el-form-item>
        <el-button id="btnQuery" type="primary" @click="getUser">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      id="rebateSetTable"
      ref="userTable"
      v-loading="isLoading"
      :data="userData"
      height="350"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        type="selection"
        width="49"
      />
      <el-table-column
        align="center"
        prop="code"
        label="用户工号"
      />
      <el-table-column
        align="center"
        prop="name"
        label="用户名"
      />
      <el-table-column
        align="center"
        prop="company.name"
        label="公司"
      />
      <el-table-column
        align="center"
        prop="department.name"
        label="部门"
      />
    </el-table>
    <el-pagination
      :current-page.sync="paginationData.pageCount"
      :page-size="paginationData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="paginationData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="assignUsers">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  commonQueryUser,
  assignUser
} from '@/api/right/role'

export default {
  name: 'DialogAssignUser',
  props: {
    isDialogAssignUserShow: {
      require: true,
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 用户信息
      userData: [],
      // 被选中的用户信息
      userDataSelection: [],
      // 当前页选中的用户信息
      currentUserDataSelection: [],
      // 被选中的用户信息表 用于跨页
      userDataSelectionForm: [],
      // 被选中的角色信息
      roleDataSelection: [],
      // 分页信息
      paginationData: {
        // 当前页面序号，默认为1
        pageCount: 1,
        // 每页数据数
        pageSize: 10,
        // 总共数据数
        total: 0,
        // 总页面数
        pages: null
      },
      // 用户查询参数
      userQuery: {
        // 用户名
        name: '',
        // 当前页面序号，默认为1
        pageNum: 1,
        // 每页数据数
        pageSize: 15,
        // 总共数据数
        total: 0
      },
      // 是否处于加载状态
      isLoading: false
    }
  },
  mounted() {
    this.$nextTick(function() {
      /**
       * 获取用户信息
       */
      this.$on('getUser', (roleDataSelection) => {
        this.roleDataSelection = roleDataSelection
        this.getUser()
      })
    })
  },
  methods: {
    /**
     * 获取用户信息
     */
    async getUser() {
      this.isLoading = true
      try {
        let res = await commonQueryUser(this.userQuery)
        if (res) {
          const { total, data } = res
          this.userData = data
          this.userQuery.total = parseInt(total)
          this.paginationData.total = parseInt(total)

          // 若本页有数据被选中，则选中
          this.$nextTick(() => {
            if (this.userDataSelectionForm[this.paginationData.pageCount - 1]) {
              const rows = this.userDataSelectionForm[this.paginationData.pageCount - 1]
              rows.forEach(row => {
                this.userData.map(item => {
                  if (item.code === row.code) {
                    this.$refs.userTable.toggleRowSelection(item, true)
                  }
                })
              })
            }
          })
        } else {
          this.$$message.error('获取用户信息失败')
        }
      } catch {
        this.$$message.error('网络错误')
      } finally {
        this.isLoading = false
      }
    },
    /**
     * 分配用户
     */
    async assignUsers() {
      if (!this.userDataSelection ||
      this.userDataSelection.length === 0) {
        this.$message.error('请至少选择一名用户')
        return
      }

      // 提供角色和用户的id，作为接口的参数
      const roleIds = []
      const userIds = []
      this.roleDataSelection.map(item => { roleIds.push(item.id) })
      this.userDataSelection.map(item => { userIds.push(item.id) })

      try {
        let res = await assignUser({ roleIds, userIds })
        if (res) {
          this.userDataSelection = []
          this.roleDataSelection = []
          this.$message.success('用户分配成功')
          this.$emit('operateRoleSuccess')
          this.closeDialog()
        } else {
          this.$message.error('用户分配失败')
        }
      } catch {
        this.$message.error('网络错误')
      }
    },
    /**
     * 关闭弹窗
     */
    closeDialog() {
      this.$emit('closeDialog')
    },
    /**
     * 更改被选中数据的数组
     * @param {*} val 被选中的数据
     */
    handleSelectionChange(val) {
      // 更新选中的数据
      val.forEach(item => {
        if (!this.currentUserDataSelection.includes(item)) {
          this.userDataSelection.push(item)
        }
      })
      this.currentUserDataSelection.forEach(item => {
        if (!val.includes(item)) {
          const index = this.userDataSelection.findIndex(v => v === item)
          this.userDataSelection.splice(index, 1)
        }
      })

      this.currentUserDataSelection = val
    },
    /**
     * 更改页面尺寸时重新获取数据
     * @param {*} val
     */
    handleSizeChange(val) {
      this.paginationData.pageSize = val
      this.userDataSelectionForm = []
      this.userDataSelection = []
      this.currentUserDataSelection = []
      this.userQuery.pageSize = val
      this.getUser(this.userQuery)
    },
    /**
     * 当前页面发生变化时重新获取数据
     * @param {*} val
     */
    handleCurrentChange(val) {
      this.userDataSelectionForm[this.userQuery.pageNum - 1] = this.currentUserDataSelection
      // 添加离去页的数据，防止遗漏
      if (this.currentUserDataSelection) {
        this.userDataSelection.push(...this.currentUserDataSelection)
      }
      // 删除到达页的数据，防止重复
      if (this.userDataSelectionForm[val - 1]) {
        this.userDataSelectionForm[val - 1].forEach(item => {
          const index = this.userDataSelection.findIndex(v => v === item)
          this.userDataSelection.splice(index, 1)
        })
      }

      this.paginationData.pageCount = val
      this.userQuery.pageNum = val
      this.getUser(this.userQuery)
    }
  }
}
</script>

<style scoped>
.searchForm{
  width: 380px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
</style>
